<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>产品添加</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="format-detection" content="telephone=no">
	<link rel="stylesheet" href="/plugins/layui/css/layui.css" media="all" />
	<link rel="stylesheet" href="/css/productsAdd.css" media="all" />
</head>
<body class="childrenBody">
<form class="layui-form" style="padding: 20px;">
	<input type="hidden" id="productId" value="">
	<div class="form-header">
		<ul>

			<li>
				<label class="layui-form-label">产品类别</label>
				<div class="layui-input-block">
					<select name="categoryId" lay-verify="required" id="categoryId">
						<option value="">--请选择产品类别--</option>
					</select>
				</div>
			</li>
			<li>
				<label class="layui-form-label">产品名称</label>
				<div class="layui-input-block">
					<input type="text" class="layui-input" lay-verify="required" name="name" placeholder="请输入产品名称" id="productName">
				</div>
			</li>
			<li>
				<label class="layui-form-label">产品价格</label>
				<div class="layui-input-block">
					<input type="text" class="layui-input" lay-verify="required||number" name="price" placeholder="请输入产品价格" id="productPrice">
				</div>
			</li>
			<li>
				<label class="layui-form-label">产品说明</label>
				<div class="layui-input-block">
					<input type="text" class="layui-input" lay-verify="required" name="description" placeholder="请输入产品说明" id="productMsg">
				</div>
			</li>
			<li>
				<label class="layui-form-label">平均耗时</label>
				<div class="layui-input-block">
					<select name="consumeTime" lay-verify="required" id="productTime">
						<option value="">--请选择平均耗时--</option>
						<option value="10">10分钟</option>
						<option value="20">20分钟</option>
						<option value="30">30分钟</option>
						<option value="40">40分钟</option>
						<option value="50">50分钟</option>
						<option value="60">60分钟</option>
						<option value="70">70分钟</option>
						<option value="80">80分钟</option>
						<option value="90">90分钟</option>
					</select>
				</div>
			</li>
		</ul>
	</div>
	<div class="table" id="form-list">
		<table class="layui-table" lay-filter="info" id="info-list">

		</table>
	</div>

	<div class="add-footer">
		<div class="add" id="add-list">添加</div>
		<div class="save" id="save">保存</div>
	</div>
</form>
<script type="text/javascript" src="/js/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="/plugins/layui/layui.js"></script>
<script type="text/html" id="delDemo">
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon"></i>删除</a>
</script>

<script type="text/javascript">
/*    layui.use('table', function(){
        var table = layui.table;
        //第一个实例
        table.render({
            elem: '#info-list'
            ,height: 600
            ,url: '/products/getById/'+id //数据接口
            ,page: false //开启分页
            ,cols: [[ //表头
                {field: 'id', title: '顺序', width:'10%', sort: true, fixed: 'left'}
                ,{field: 'sex', title: '工序名称', width:'10%', sort: true}
                ,{field: 'city', title: '介绍', width:'68%'}
                ,{field: 'sign', title: '操作', width: '10%'}
            ]]
        });
    });*/

    var categorysList;
    $.ajax({
        type : "GET",
        url: '/categorys/getAllCategorys',
        dataType:'json',
        async:false,
        success: function(data){
            var list=data.data;
            regionsList=list;
            var html='';
            for(var i=0;i<list.length;i++){
                html += "<option value='"+list[i].id+"'>"+list[i].name+"</option>"
            }
            $("#categoryId").append(html);
        }
    });

layui.config({
    base : "/js/admin/"
}).extend({
    $tool: 'tool'
}).use(['form','layer','jquery','$tool','table'],function(){
        var form = layui.form,
            layer = parent.layer === undefined ? layui.layer : parent.layer,
            $ = layui.jquery,
			$tool=layui.$tool,
			table=layui.table;
   	 var tabledata;
   	 var toDeleteWsIds=[];
    var queryArgs = $tool.getQueryParam();//获取查询参数
    var id = queryArgs['id'];
        initProductInfo();
        /**
         * 初始化用户信息
         * */
        function initProductInfo() {
            var url = '/products/getById/'+id;
            $.ajax({
                url:url,
                method:"GET",
				async:false,
                success:function (data) {
                    if(data.code==2000){
                        var datas = data.data;
                        $("#productId").val(datas.id);
                        $("input[name='name']").val(datas.name);
                        $("input[name='price']").val(datas.price);
                        $("input[name='description']").val(datas.description);
                        $("#categoryId option[value='"+datas.categoryId+"']").attr("selected","selected");
                        $("#productTime option[value='"+datas.consumeTime+"']").attr("selected","selected");
                        form.render();//重新绘制表单，让修改生效

						tabledata=datas.workstageList;

                    }

                }
            });
        }
    table.render({
        elem: '#info-list'
        ,data: tabledata
        ,page: false //开启分页
        ,cols: [[ //表头
            {field: 'sort', title: '排序(必填)', sort: true, fixed: 'left',edit: 'text'}
            ,{field: 'name', title: '工序名称(必填)', edit: 'text'}
            ,{field: 'description', title: '介绍(选填)',edit: 'text'}
            ,{title: '操作', align:'center', toolbar: '#delDemo'}
        ]]
        ,limit:100
    });

    //监听单元格编辑
    table.on('edit(info)', function(obj){

        var value = obj.value //得到修改后的值
            ,data = obj.data //得到所在行所有键值
            ,field = obj.field; //得到字段
        var d;
        var reg = /^[1-9]\d*$/;
        if(data.sort!=''){
            var oldValue=$(this).prev().text();
            if(!reg.test(obj.data.sort)){
                obj.data.sort=oldValue;
                table.reload('info-list',{
                    data : tabledata
                });
                layer.msg("顺序请输入正整数")
            }
        }
        tabledata[data.LAY_TABLE_INDEX] = data;

    });
    /**
     * 删除某一行
     * **/
    table.on('tool(info)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        var data = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var tr = obj.tr; //获得当前行 tr 的DOM对象
        console.log(tr.selector);
        if(layEvent === 'detail'){ //查看
            //do somehing
        } else if(layEvent === 'del'){ //删除
            layer.confirm('真的删除行么', function(index){
                let str = tr.selector.split('"');
                console.log(tabledata[parseInt(str[1])]);


               if(tabledata[parseInt(str[1])].id !=undefined){
                   toDeleteWsIds.push(tabledata[parseInt(str[1])].id) ;
			   }
                tabledata.splice(parseInt(str[1]),1);
                table.reload('info-list',{
                    data : tabledata
                });
                layer.close(index);
                //向服务端发送删除指令
            });
        } else if(layEvent === 'edit'){ //编辑
            //do something

            //同步更新缓存对应的值
            obj.update({
                username: '123'
                ,title: 'xxx'
            });
        }
    });

		/**
		 * 动态添加列表
		 * **/
		$("#add-list").click(function(){
			console.log(tabledata);
			var data1={"id":"","sort":"","name":"","description":""};
			tabledata.push(data1);
			table.reload('info-list',{
				data : tabledata
			});
		})

    /**
     * 保存
     * **/
    $("#save").bind("click",function(){
        var obj = {}
        if($("#categoryId").val() == ""){
            layer.msg('请选择产品类别');
            return;
        }else if($("#productName").val() ==""){
            layer.msg('请输入产品名称');
            return;
        }else if($("#productPrice").val() == ""){
            layer.msg('请输入产品价格');
            return;
        }else if($("#productMsg").val() ==""){
            layer.msg('请输入产品说明');
            return;
        }else if($("#productTime").val() == ""){
            layer.msg('请选择消耗时间');
            return;
        }
        obj.id=id;
        obj.categoryId = parseInt($("#categoryId").val());
        obj.name = $("#productName").val();
        obj.price = parseInt($("#productPrice").val());
        obj.description = $("#productMsg").val();
        obj.consumeTime = $("#productTime").val();
        for(var i in tabledata){

            if(tabledata[i].sort==''){
                layer.msg('请填写工序顺序');
                return;
            }else if(tabledata[i].name==''){
                layer.msg('请填写工序名称');
                return;
            }else if(tabledata[i].name.length>20){
                layer.msg('名称最多20个字符');
                return;
            }
            tabledata[i].sort = parseInt(tabledata[i].sort);
        }
        obj.workstageList = tabledata;
		obj.toDeteleWsIds=toDeleteWsIds;
        console.log(obj)
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
        $.ajax({
            type: "POST",
            data:JSON.stringify(obj),
            url:"/products",
            contentType : 'application/json',
            success: function(result) {
                console.log(result);
                if(result.code==2000){
                    top.layer.close(index);
                    top.layer.msg("修改成功！");
                    top.layer.closeAll("iframe");
                    parent.location.reload();
                }else{
                    top.layer.msg(result.msg);
                }
            } ,
            error: function(request) {
                alert("Connection error");
            }
        });
    })

    })

</script>
</body>
</html>

